package org.easy.tool.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class EasyRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public EasyRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = getBodyString(request).getBytes(StandardCharsets.UTF_8);
    }

    private static String getBodyString(ServletRequest request) {
        //代码示例
        StringBuilder sb = new StringBuilder();
        try {
            InputStream inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                ObjectMapper mapper = new ObjectMapper();
                Object infoBean = mapper.readValue(line, Object.class);
                //TODO
                String info = mapper.writeValueAsString(infoBean);
                sb.append(info);
            }
            inputStream.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream in = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return in.read();
            }

            public boolean isFinished() {
                return false;
            }

            public boolean isReady() {
                return false;
            }

            public void setReadListener(ReadListener param) {
                System.out.println(param);
            }
        };
    }

}
